package com.whereta.controller;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Producer;
import com.whereta.enums.SessionEnum;
import com.whereta.service.IAccountService;
import com.whereta.shiro.RedisManager;
import com.whereta.utils.DataUtil;
import com.whereta.vo.LoginVO;
import com.whereta.vo.ResultVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Vincent
 * @time 2015/8/12 13:49
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    private IAccountService accountService;
 /*   @Resource
    private JmsTemplate jmsTemplate;*/
    @Resource
    private RedisManager redisManager;

    @Resource
    private Producer captchaProducer;

    //跳转到用户管理页面
    @RequestMapping("/manage")
    public String manage() {
        return "user/manage";
    }

    //用户管理  获取数据
    @RequestMapping(value = "/get-manage-user", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultVO getManageUser(int page, int rows) {
        Object principal = SecurityUtils.getSubject().getPrincipal();
        ResultVO resultVO = accountService.selectAccount(Integer.parseInt(principal.toString()), page, rows);
        return resultVO;
    }

    //跳转到登录页面
    @RequestMapping("/login")
    public String login() {
        return "user/login";
    }

    //退出
    @RequestMapping("/exit")
    public String exit() {
        SecurityUtils.getSubject().logout();
        return "user/login";
    }

    //验证码图片
    @RequestMapping("/authCode")
    public void authCode(HttpServletResponse response, HttpSession session) throws IOException {
        String text = captchaProducer.createText();
        BufferedImage image = captchaProducer.createImage(text);
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image, "JPG", outputStream);
        session.setAttribute(SessionEnum.VERIFYCODE.toString(), text);
        outputStream.flush();
        outputStream.close();
    }

    //验证登录
    @RequestMapping(value = "/check-login", method = RequestMethod.POST)
    public
    @ResponseBody
    ResultVO checkLogin(@Valid @ModelAttribute final LoginVO loginVO, BindingResult bindingResult, HttpSession session, HttpServletRequest request) {
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        ResultVO resultVO = new ResultVO(true);

        if (fieldErrors != null && !fieldErrors.isEmpty()) {
            String defaultMessage = fieldErrors.get(0).getDefaultMessage();
            resultVO.setOk(false);
            resultVO.setMsg(defaultMessage);
            return resultVO;
        }
        //验证验证码
        Object verifyCodeObj = session.getAttribute(SessionEnum.VERIFYCODE.toString());
        if (verifyCodeObj == null) {
            resultVO.setOk(false);
            resultVO.setMsg("验证码已过期");
            return resultVO;
        }

        if (!verifyCodeObj.toString().equalsIgnoreCase(loginVO.getVerifycode())) {
            resultVO.setOk(false);
            resultVO.setMsg("验证码错误");
            return resultVO;
        }
        //验证登录
        AuthenticationToken token = new UsernamePasswordToken(loginVO.getAccount(), loginVO.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            resultVO.setOk(false);
            resultVO.setMsg("账号或者密码错误");
            return resultVO;
        }
        //删除验证码
        session.removeAttribute(SessionEnum.VERIFYCODE.toString());

        final String ip = DataUtil.getIpAddr(request);

        //发送日志
     /*   jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                MapMessage message = session.createMapMessage();
                message.setString("type", "login");
                message.setString("account", loginVO.getAccount());
                message.setString("ip", ip);
                message.setString("logintime", String.valueOf(System.currentTimeMillis()));
                return message;
            }
        });*/
        Map<String,String> message=new HashMap<>();
        message.put("type", "login");
        message.put("account", loginVO.getAccount());
        message.put("ip", ip);
        message.put("logintime", String.valueOf(System.currentTimeMillis()));
        redisManager.publish("logs", JSON.toJSONString(message));


        return resultVO;
    }
}
